<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->

    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->

    <a-tabs v-model="activeKey">
      <a-tab-pane key="ll" tab="发出商品出库单">
        <div>
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="">
                    <j-input type="like" v-model="ext1"></j-input>
                    <!--                    <a-input placeholder="" type="like" v-model="ext1"></a-input>-->
                    <!--                    <j-dict-select-tag type="list" v-model="queryParam.businessType"-->
                    <!--                                       dictCode="business_type" placeholder="请选择业务类型"/>-->
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQueryTab1" icon="search">搜索</a-button>
                    <!--                    <a-button type="primary" @click="searchResetTab1" icon="reload" style="margin-left: 8px">重置</a-button>-->
                    <a-button type="primary" @click="addNotice" icon="reload" style="margin-left: 8px">添加出库单</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <!--          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
          <!--            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
          <!--            <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
          <!--          </div>-->
          <a-table
            ref="procTable"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap"
            :scroll="{x:true}"
            :columns="table1.columns"
            :dataSource="table1.dataSource"
            :pagination="table1.ipagination"
            :loading="table1.loading"
            :rowSelection="{selectedRowKeys: table1.selectedRowKeys, onChange: onSelectChangeTab1}"
          >
          </a-table>
        </div>
      </a-tab-pane>
      <a-tab-pane key="ck" tab="出库单" force-render>    <!-- table区域-begin -->
        <!-- table区域-begin -->
        <div>
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="10" :lg="11" :md="12" :sm="24">
                  <a-form-item label="出库日期">
                    <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParam.outboundDate_begin"></j-date>
                    <span class="query-group-split-cust"></span>
                    <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParam.outboundDate_end"></j-date>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div class="table-operator">
            <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
            <a-button type="primary" icon="download" @click="handleExportXls('出库单管理')">导出</a-button>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" icon="import">导入</a-button>
            </a-upload>
            <a-button type="primary" icon="printer" @click="openPrintPreview">打印预览</a-button>
            <!-- 高级查询区域 -->
            <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
            <a-dropdown v-if="selectedRowKeys.length > 0">
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
              </a-menu>
              <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
            </a-dropdown>
          </div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            <a-popover title="自定义列" trigger="click" placement="leftBottom" style="float: right">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row>
                    <template v-for="(item,index) in defColumns">
                      <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                        <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />自定义列</a>
            </a-popover>
          </div>
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="">
                    <!--                  <j-input v-model="ext2" @change="handleInputChange"></j-input>-->
                    <!--                    <a-input placeholder="" type="like" v-model="ext1"></a-input>-->
                    <!--                    <j-dict-select-tag type="list" v-model="queryParam.businessType"-->
                    <!--                                       dictCode="business_type" placeholder="请选择业务类型"/>-->
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text,record">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
          <a v-if="record.status == 0" @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
    <buss-package-outbound-order-management-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import BussPackageOutboundOrderManagementModal from './modules/BussPackageOutboundOrderManagementModal'
import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import store from '@/store'
import { getAction, deleteAction } from '@/api/manage'
import moment from 'dayjs'

export default {
  name: "BussPackageOutboundOrderManagementList",
  mixins:[JeecgListMixin],
  components: {
    BussPackageOutboundOrderManagementModal
  },
  data () {
    return {
      description: '出库单管理管理页面',
      ext1:'',
      activeKey: "ll",
      table1:{
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'出库类型',
            align:"center",
            dataIndex: 'type'
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'code'
          },
          {
            title:'主备注',
            align:"center",
            dataIndex: 'zremark'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title:'仓库名称',
            align:"center",
            dataIndex: 'erpWarehouseName'
          },
          {
            title:'产品编号',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'客户产品编号',
            align:"center",
            dataIndex: 'customMaterialCode'
          },
          {
            title:'产品名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'spec'
          },
          {
            title:'主计量',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title:'数量',
            align:"center",
            dataIndex: 'quantity'
          },
          {
            title:'库存可用数量',
            align:"center",
            dataIndex: 'procurementArrayPrice'
          },
          {
            title:'辅助计量',
            align:"center",
            dataIndex: 'auUnit'
          },
          {
            title:'辅助数量',
            align:"center",
            dataIndex: 'auQuantity'
          },
          {
            title:'制单人',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'制单日期',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title:'制单部门',
            align:"center",
            dataIndex: 'sysOrgCode'
          },
        ],
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
      },
      // 表头
      columns: [],
      settingColumns: [],
      // 表头
      defColumns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'单据编号',
          align:"center",
          dataIndex: 'code'
        },
        {
          title:'出库类型',
          align:"center",
          dataIndex: 'outboundType_dictText'
        },
        {
          title:'仓库',
          align:"center",
          dataIndex: 'warehouseId_dictText'
        },
        {
          title:'上级单号',
          align:"center",
          dataIndex: 'superiorOrderNumber'
        },
        {
          title:'出库日期',
          align:"center",
          dataIndex: 'outboundDate',
          customRender:function (text) {
            return !text?"":(text.length>10?text.substr(0,10):text)
          }
        },
        {
          title:'供应商',
          align:"center",
          dataIndex: 'supplierId_dictText'
        },
        {
          title:'客户名称',
          align:"center",
          dataIndex: 'cutomerName'
        },
        {
          title:'部门车间',
          align:"center",
          dataIndex: 'departmentWorkshop_dictText'
        },
        {
          title:'备注',
          align:"center",
          dataIndex: 'remark'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' },
        }
      ],
      url: {
        list: "/outbound/bussPackageOutboundOrderManagement/list",
        delete: "/outbound/bussPackageOutboundOrderManagement/delete",
        deleteBatch: "/outbound/bussPackageOutboundOrderManagement/deleteBatch",
        exportXlsUrl: "/outbound/bussPackageOutboundOrderManagement/exportXls",
        importExcelUrl: "outbound/bussPackageOutboundOrderManagement/importExcel",
        proclist: "/business/bussMaterialProcurement/page/list",
        revokeUrl: "/quality/bussMaterialProcurement/revokeBatch",
      },
      dictOptions:{},
      superFieldList:[],
    }
  },
  created() {
    this.getSuperFieldList();
    this.initColumns();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    searchQueryTab1(){
      // this.loadProcData();
    },
    addNotice(){
      const rows = this.table1.selectionRows;
      if(rows.length == 0){
        this.$message.warn('请选择领料单！')
        return;
      }

      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
      // 添加入库通知单
      this.$nextTick(()=>{
        this.$refs.modalForm.$refs.realForm.procSelectRows = rows
        this.$refs.modalForm.$refs.realForm.addProc()
      })
    },
    getProcQueryParams() {
      //获取查询条件
      var param = {};
      // param.field = this.getQueryField();
      param.ext1 = this.ext1
      param.pageNo = this.table1.ipagination.current;
      param.pageSize = this.table1.ipagination.pageSize;
      return filterObj(param);
    },
    loadProcData(){
      //加载数据 若传入参数1则加载第一页的内容
      // if (arg === 1) {
      //   this.ipagination.current = 1;
      // }
      // var params = {}
      var params = this.getProcQueryParams();//查询条件
      this.table1.loading = true;
      getAction(this.url.proclist, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.table1.dataSource = res.result.records || res.result;
          if (res.result.total) {
            this.table1.ipagination.total = res.result.total;
          } else {
            this.table1.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.table1.loading = false
      })
    },
    onSelectChangeTab1(selectedRowKeys, selectionRows) {
      this.table1.selectedRowKeys = selectedRowKeys;
      this.table1.selectionRows = selectionRows;
    },
    initDictConfig(){
    },
    getSuperFieldList(){
      let fieldList=[];
      fieldList.push({type:'string',value:'code',text:'单据编号',dictCode:''})
      fieldList.push({type:'string',value:'outboundType',text:'出库类型',dictCode:'ck_type'})
      fieldList.push({type:'string',value:'warehouseId',text:'仓库',dictCode:"erp_warehouse,name,id"})
      fieldList.push({type:'string',value:'superiorOrderNumber',text:'上级单号',dictCode:''})
      fieldList.push({type:'date',value:'outboundDate',text:'出库日期'})
      fieldList.push({type:'string',value:'supplierId',text:'供应商',dictCode:"erp_supplier,name,id"})
      fieldList.push({type:'string',value:'cutomerName',text:'客户名称',dictCode:''})
      fieldList.push({type:'string',value:'departmentWorkshop',text:'部门车间',dictCode:"sys_depart,depart_name,id"})
      fieldList.push({type:'Text',value:'remark',text:'备注',dictCode:''})
      fieldList.push({type:'datetime',value:'createTime',text:'创建日期'})
      this.superFieldList = fieldList
    },
    handleInputChange(event) {
      this.loading = true
      let params = this.getQueryParams()
      params.hasQuery = 'true'
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records || res.result;
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
        this.changeColor(event)
      })
    },
    changeColor(event) {
      console.log(event);
      var msg = event.replaceAll('*','');
      console.log(msg);
      // 这里可以添加你的逻辑代码
      const text = this.dataSource;
      let str = JSON.stringify(this.dataSource);
      console.log(str);
      const highlightedKeyword = str.replaceAll(new RegExp(msg, 'g'), `<span style='background-color: yellow;font-weight: bold;'>${msg}</span>`);
      this.dataSource = JSON.parse(highlightedKeyword);
    },
    openPrintPreview() {
      if (  this.selectedRowKeys.length<1){
        this.$message.error("请选择后再预览")
        return
      }
      if (  this.selectedRowKeys.length>1){
        this.$message.error("打印预览时最多只能选择一条记录")
        return
      }

      let token = store.getters.token
      let id = this.selectedRowKeys[0]
      console.log("预览")
      this.$router.push({path:'/business/outbound/PrintPreview',query: {id:id,token:token,serviceName:'bussPackageOutboundOrderManagement',moduleName:'outbound' }})
    },
    onRadioChange() {
      this.loadData()
    },
    revokeInfo() {
      if (  this.selectedRowKeys.length<1){
        this.$message.error("请选择要撤销的出库单")
        return
      }
      var ids = "";
      for (var a = 0; a < this.selectedRowKeys.length; a++) {
        ids += this.selectedRowKeys[a] + ",";
      }
      var that = this;
      getAction(that.url.revokeUrl, {ids: ids}).then((res) => {
        if (res.success) {
          that.searchQuery();
        }
      }).finally(() => {

      });
    },
    changeDate() {
      this.$forceUpdate()
    },
    searchReset(num) {
      let that = this;

      if (num !== 0) {
        that.queryParam = {
          status: 1,
          outboundDate_begin : moment().subtract(7, 'days').format(this.dateFormat),
          outboundDate_end : moment().format(this.dateFormat)
        };
        that.loadData(1);
      }
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.highlight {
  color: red; /* 指定字体颜色为红色 */
}
</style>